package com.renli.service.impl;

import com.renli.bean.ResultJson;
import com.renli.mapper.SalaryMapper;
import com.renli.pojo.Salary;
import com.renli.service.SalaryService;
import com.sun.org.apache.regexp.internal.RE;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class SalaryServiceImpl implements SalaryService {

    @Autowired
    private SalaryMapper salaryMapper;

    @Override
    public ResultJson<List<Salary>> findAll(Map<String, Integer> map) {

        map.putIfAbsent("currentPage", 1);
        map.putIfAbsent("pageSize", 6);
        Integer start = map.get("pageSize") * (map.get("currentPage") - 1);
        map.put("start", start);
        List<Salary> salaryList = salaryMapper.findAll(map);
        Long total = salaryMapper.findAllCount();
        ResultJson<List<Salary>> resultJson = new ResultJson<>();
        resultJson.setSuccess("查询成功", salaryList, total);


        return resultJson;
    }

    @Override
    public ResultJson del(List<Integer> list) {
        if (salaryMapper.del(list) > 0) {
            return new ResultJson().setSuccess("删除成功");
        }else {
            return new ResultJson().setSuccess("删除失败");
        }
    }

    /**
     * 保存操作
     * 效率低，待改善
     * @param list
     * @return
     */
    @Override
    public ResultJson update(List<Salary> list) {

        int size = list.size();
        long l = Long.parseLong(size + "");
        int m = 0;
        String msgm = "";
        String msgn = "";
        Long allCount = salaryMapper.findAllCount();
        if (size>l){

            int n = 0;
           //有新增数据
            for (int i = 0; i < list.size(); i++) {
           //修改原始数据
                if (i<allCount){
                  m+=  salaryMapper.update(list.get(i));
                }else {
                    //新增
                   n+= salaryMapper.add(list.get(i));
                }

            }


            if (m>0){
                msgm = "修改成功";
            }
            if (n>0){
                msgn = "新增成功";
            }

       }else {
            //没有新增数据
            //修改
            for (Salary salary : list) {
               m+= salaryMapper.update(salary);
            }
            if (m>0){
                msgm = "修改成功";
            }

        }

        ResultJson resultJson = new ResultJson();
        resultJson.setSuccess(msgm + msgn);
        return resultJson;
    }
}
